package com.yq.leetcodeOld.array;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName TwoSum
 * @Description 两数之和，利用hashmap， map。containKey(target-num[i]),存在就返回，不存在就存入，最后结果还得return new int[0]
 * @Author yaoqiang
 * @Date 2022/4/7 10:38
 * @Version 1.0
 */
public class TwoSum {
    public static void main(String[] args) {
        //输入：nums = [2,7,11,15], target = 9
        //输出：[0,1] 因为 nums[0] + nums[1] == 9 ，返回 [0, 1] 。
        int[] nums= new int[]{2,7,11,15};
        int target = 9;
        twosum(nums , target);
    }

    private static int[] twosum(int[] nums, int target) {
        Map<Integer,Integer> map=new HashMap<>();
        for (int i=0;i<nums.length;i++){
            if (map.containsKey(target-nums[i])){
                return new int[]{map.get(target-nums[i]),i};
            }else {
                map.put(nums[i],i);
            }
        }
        return new int[0];
    }
}
